package com.ysu.shop.client;

import com.auth0.jwt.JWT;
import com.ysu.shop.pojo.User;
import com.ysu.shop.service.IUserService;
import com.ysu.shop.utils.JwtUtil;
import com.ysu.shop.utils.Result;
import com.ysu.shop.utils.ShaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserControl {
    
    @Resource
    private IUserService userService;

    @GetMapping("/info")
    public Result getUserById(HttpServletRequest request){
        User user = userService.getUserById(JwtUtil.getUserId(request));
        return Result.getSuccessResult(user);
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user,HttpServletRequest request) {
        int userId = JwtUtil.getUserId(request);
        if (!StringUtils.isEmpty(user.getPassword())){
            user.setPassword(null);
        }
        if (!StringUtils.isEmpty(user.getUsername())){
            user.setUsername(null);
        }
        if (!StringUtils.isEmpty(user.getAnswer())){
            user.setAnswer(null);
        }
        if (!StringUtils.isEmpty(user.getQuestion())){
            user.setQuestion(null);
        }
        if (userService.updateById(user)){
            return Result.getSuccessResult("","修改成功");
        }
        return Result.getFailResult("","修改失败");
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,Object> param, HttpServletRequest request) {
        int userId = JwtUtil.getUserId(request);
        String oldPwd = ShaUtil.getSHA256(param.get("oldPwd").toString());
        String newPwd = ShaUtil.getSHA256(param.get("newPwd").toString());
        if (userService.updatePwd(userId,oldPwd,newPwd)>0){
            return Result.getSuccessResult("","修改密码成功");
        }
        return Result.getFailResult("","原密码不正确,修改密码失败");
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @PutMapping("/updatePwdByAnswer")
    public Result updatePwdByAnswer(@RequestBody Map<String,Object> param, HttpServletRequest request) {
        int userId = JwtUtil.getUserId(request);
        String answer = ShaUtil.getSHA256(param.get("answer").toString());
        String newPwd = ShaUtil.getSHA256(param.get("newPwd").toString());
        if (userService.updatePwdByAnswer(userId,answer,newPwd)>0){
            return Result.getSuccessResult("","修改密码成功");
        }
        return Result.getFailResult("","修改密码失败");
    }
}
